package com.firesafe.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.firesafe.common.dto.LoginDTO;
import com.firesafe.common.dto.RegisterDTO;
import com.firesafe.common.entity.UserEntity;
import com.firesafe.common.exception.RRException;
import com.firesafe.common.utils.PageUtils;
import com.firesafe.common.utils.Query;
import com.firesafe.common.vo.LoginVO;
import com.firesafe.user.dao.UserDao;
import com.firesafe.user.service.UserService;
import com.firesafe.user.utils.TokenUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    //分页查询
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    //注册
    @Override
    public void register(RegisterDTO registerDTO) {
        //检验合法性
        if(registerDTO.getUserName()==null || registerDTO.getPassword()==null || registerDTO.getRole()==null){
            throw new RRException("数据输入不合法");
        }
        //用户名不能重复
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", registerDTO.getUserName());
        if(this.getOne(queryWrapper)!=null) {
            throw new RRException("用户名已存在");
        }
        //新增用户
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(registerDTO, userEntity);
        userEntity.setCreateTime(new Date());
        userEntity.setUpdateTime(new Date());
        this.save(userEntity);
    }

    //登录
    @Override
    public LoginVO login(LoginDTO loginDTO) {
        //检验数据合法性
        if(loginDTO.getUserName()==null || loginDTO.getPassword()==null){
            throw new RRException("数据输入不合法");
        }
        //查找用户
        QueryWrapper<UserEntity> wrapper=new QueryWrapper<>();
        wrapper.eq("user_name",loginDTO.getUserName());
        UserEntity user=this.getOne(wrapper);
        //检验用户名和密码
        if(user==null){
            throw new RRException("用户名或密码错误");
        }
        if(!user.getPassword().equals(loginDTO.getPassword())){
            throw new RRException("用户名或密码错误");
        }
        //生成token
        String token= TokenUtils.createToken(user.getId().toString(),user.getPassword());
        user.setToken(token);
        //返回当前登录用户
        LoginVO vo=new LoginVO();
        BeanUtil.copyProperties(user,vo);
        return vo;
    }
}
